<template>
    <div class="sys-perm p-4 bg-white rounded-lg shadow-sm border border-gray-200">
        <!-- Header -->
        <h2 class="text-lg font-medium pb-2">权限列表</h2>
        <el-form ref="formRef" :model="queryParams" :rules="formRules" inline inline-message>
            <el-form-item label="权限名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入权限名称"/>
            </el-form-item>
            <el-form-item label="权限类型" label-width="80px" prop="type">
                <el-select v-model="queryParams.type" :fit-input-width="false" placeholder="所有"
                           style="width: 120px;">
                    <el-option :value="'M'" label="菜单"/>
                    <el-option :value="'P'" label="功能"/>
                </el-select>
            </el-form-item>
            <el-form-item label="权限状态" label-width="80px" prop="status">
                <el-select v-model="queryParams.status" :fit-input-width="false" placeholder="全部"
                           style="width: 120px;">
                    <el-option :value="1" label="启用"/>
                    <el-option :value="0" label="禁用"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <template #default>
                    <el-button :icon="'Search'" type="primary" @click="search">搜索</el-button>
                    <el-button :icon="'RefreshRight'" plain type="info"
                               @click="reset">重置
                    </el-button>
                </template>
            </el-form-item>
        </el-form>
        <div class="flex flex-wrap justify-between items-center pb-2 gap-2">
            <!-- 左侧操作 -->
            <div class="flex flex-wrap gap-2">
                <el-button
                    icon="Plus"
                    plain type="primary"
                    @click="handleAdd" v-permission:perm:insert
                >
                    新增
                </el-button>
                <!--                <el-button :disabled="selectedRow.length === 0" icon="Delete" plain type="danger"-->
                <!--                           @click="handleBatchDelete">-->
                <!--                    批量删除-->
                <!--                </el-button>-->
            </div>
            <!-- 右侧工具 -->
            <div class="flex flex-wrap gap-2">
                <!--                <el-button icon="Refresh" @click="refresh">刷新</el-button>-->
                <!--                <el-button icon="Setting" type="text" @click="openColumnSetting">列设置</el-button>-->
            </div>
        </div>
        <div style="position: relative">
            <el-table
                ref="tableRef"
                v-loading="loading"
                :data="permissionList"
                :row-key="'id'"
                :tree-props="{children: 'children', hasChildren: 'hasChildren', checkStrictly: true}"
                border
                default-expand-all
                height="800px"
                show-overflow-tooltip
                @selection-change="onSelectionChange"
            >
                <template #default>
                    <!--                    <el-table-column :align="'center'" fixed type="selection" width="55px"/>-->
                    <el-table-column v-for="(item, index) in tableColumns" :key="item.prop"
                                     :align="item.align || 'left'"
                                     :fixed="item.fixed" :label="item.label" :min-width="item.min_width"
                                     :prop="item.prop"
                                     :sortable="item.sortable" :width="item.width">
                        <template #default="{row, column}">
                            <div v-if="item.type === 'switch'">
                                <el-switch v-model="row[item.prop]" :active-value="item.activeValue"
                                           :inactive-value="item.inactiveValue"
                                           @change="onSwitchChange(row)">
                                </el-switch>
                            </div>
                            <div v-else-if="item.type === 'status'">
                                <el-tag :type="item.color ? item.color[row[item.prop]] : 'primary'">
                                    {{ activeStatus(item.option, row[item.prop]) }}
                                </el-tag>
                            </div>
                            <div v-else-if="item.type === 'image'">
                                <el-image :preview-src-list="[row[item.prop]]" :src="row[item.prop]"
                                          style="width: 60px; height: 60px">
                                </el-image>
                            </div>
                            <div v-else-if="item.type === 'icon'">

                                <el-icon v-if="row[item.prop]!==null||row[item.prop]!==''" size="small">
                                    <template #default>
                                        <component :is="row[item.prop]"/>
                                    </template>
                                </el-icon>
                            </div>
                            <div v-else-if="item.type === 'time'">{{ row[item.prop] }}</div>
                            <template v-else>{{ row[item.prop] }}</template>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="200px">
                        <template #default="{row}">
                            <div>
                                <el-button :icon="'EditPen'" plain size="small" type="primary" @click="handleEdit(row)" v-permission:perm:update="row">
                                    编辑
                                </el-button>
                                <el-button :icon="'Delete'" size="small" type="danger" @click="handleDelete(row)" v-permission:perm:delete="row">删除
                                </el-button>
                            </div>
                        </template>
                        <template #header></template>
                        <template #expand></template>
                        <template #filter-icon></template>
                    </el-table-column>
                </template>
                <template #append>
                    <div class="data-to-bottom" style="height: 200px">
                        已经到底了
                    </div>
                </template>
            </el-table>
        </div>

        <el-dialog ref="dialogRef" v-model="isVisible.visible" :before-close="close" :lock-scroll="true"
                   :title="isVisible?.title">
            <router-view v-if="isVisible?.visible" v-slot="{Component}">
                <component :is="Component" :data="isVisible?.data" @cancel="close" @submit="submit"></component>
            </router-view>
        </el-dialog>
    </div>
</template>

<script setup>
import {computed, reactive, ref} from "vue";
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from "element-plus";
import useSysPermission from "@/composables/useSysPermission.js";
import instance from "@/api/request.js";

onMounted(() => {
    search();
})
const {
    queryParams,
    permissionList,
    current,
    total,
    size,
    loading,
    search,
    reset,
    refresh,
} = useSysPermission();

const selectedRow = ref([])

const isExpanded = ref(true);
const onSelectionChange = (selection) => {
    selectedRow.value = selection;
}

const onSwitchChange = (row) => {

}

const activeStatus = (option, value) => {
    return option[value];
}

const handleAdd = () => {
    // 这里可以添加逻辑来处理插入操作
    dialogVisible.insert.visible = true;
    router.push("/perm/add");
}

const handleEdit = (row) => {
    // 这里可以添加逻辑来处理更新操作
    dialogVisible.update.visible = true;
    dialogVisible.update.title = `修改权限菜单 - ${row.title}`;
    dialogVisible.update.data = row; // 将行数据传递给更新对话框
    router.push(`/perm/edit/${row.id}`);
}

const handleDelete = (row) => {
// 这里可以添加逻辑来处理删除操作
    ElMessageBox.confirm(
        `确定要删除权限菜单 ${row.name} 吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        instance.delete(`/permission/del/${row.id}`).then(res => {
            if (res.code === 200) {
                ElMessage.success(`权限菜单 ${row.name} 删除成功`);
            } else {
                ElMessage.error(res.data);

            }
            search();
        })
    }).catch(() => {
        console.log('取消删除');
    });
}

const handleBatchDelete = () => {

}

const openColumnSetting = () => {

}

// 模态框表单提交
const submit = (formData) => {
    close();
}

// 取消
const close = () => {
    router.push({path: "/perm"});// 返回到字典列表页面
    handleClose(() => {
        search();
    });
}

const router = useRouter();
const formRef = ref();
const formRules = reactive({})

// 表格
const tableRef = ref();
const tableColumns = ref([
    {prop: 'id', label: "编号", width: '120px', fixed: true},
    {prop: 'name', label: '权限名称', sortable: true, fixed: true, min_width: '120px'},
    {prop: 'path', label: '权限路径', min_width: '180px'},
    {prop: 'component', label: '组件路径', min_width: '180px'},
    {prop: 'icon', label: '图标', type: 'icon', align: "center"},
    {prop: 'title', label: '权限标题', width: '200px'},
    {prop: 'apiPath', label: 'API路径'},
    {prop: 'perms', label: '权限标识', width: '120px'},
    {
        prop: 'type', label: '权限类型', width: '100px', type: 'status', option: {
            'M': '菜单',
            "P": '功能'
        },
        color: {
            'M': 'primary',
            'P': 'info'
        }
    },
    {prop: 'parentId', label: '父权限编号', width: '120px'},
    {prop: 'parentName', label: '父权限名称'},
    {prop: 'sort', label: '排序', width: '80px', sortable: true},
    {
        prop: 'status',
        label: '状态',
        width: '80px',
        type: 'status',
        show: true,
        align: 'center',
        option: {
            '1': '启用',
            '0': '停用'
        },
        color: {
            '1': 'success',
            '0': 'danger',
        }
    },
    {
        prop: 'hidden', label: '是否隐藏', type: 'status', width: '100px', option: {
            '1': '已隐藏',
            '0': '未隐藏',
        },
        color: {
            '1': 'warning',
            '0': 'primary',
        },
        activeValue: 1,
        inactiveValue: 0,
    },
    // {prop: 'createBy', label: '创建人', width: '100px'},
    {prop: 'createTime', label: '创建时间', width: '180px', sortable: true},
    // {prop: 'updateBy', label: '更新人', width: '100px'},
    {prop: 'updateTime', label: '更新时间', width: '180px', sortable: true}
])
const tableData = ref([]);
const dialogRef = ref();
// 模态框models，显示多个模态框的model
const dialogVisible = reactive({
    default: {
        visible: false,
        type: 'default',
        title: '',
        data: null
    },
    insert: {
        visible: false,
        type: 'insert',
        title: '添加权限菜单',
        data: null // 用于存储插入时的行数据
    },
    update: {
        visible: false,
        type: 'update',
        title: '修改权限菜单',
        data: null // 用于存储更新时的行数据
    }
});

const handleClose = (done) => {
    dialogVisible.insert.visible = false;
    dialogVisible.update.visible = false;
    done()
}

const isVisible = computed(() => {
    // 这里可以添加逻辑来判断哪个对话框应该显示
    if (dialogVisible.insert.visible) return dialogVisible.insert;
    if (dialogVisible.update.visible) return dialogVisible.update;
    return dialogVisible.default;
})

</script>

<style lang="scss" scoped>
:deep(.el-table) .table-header,
:deep(.el-table) .table-header-row {
    color: #0f0f0f;
    font-weight: bold;
    background-color: #f0f0f0
}

.data-to-bottom {
    color: #999;
    padding: 20px;
    position: absolute;
    text-align: center;
    width: 100%;
    height: 100px;
}
</style>